package com.zhj.controller;

import com.zhj.mapper.MyUserDetailsServiceMapper;
import com.zhj.model.AjaxResponse;
import com.zhj.model.CustomException;
import com.zhj.model.CustomExceptionType;
import com.zhj.model.SmsCode;
import com.zhj.po.MyUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@RestController
public class SmsController {

    @Resource
    MyUserDetailsServiceMapper myUserDetailsServiceMapper;


    //获取短信验证码
    @RequestMapping(value="/smscode",method = RequestMethod.GET)
    public AjaxResponse sms(@RequestParam String mobile, HttpSession session) throws IOException {

        MyUserDetails myUserDetails = myUserDetailsServiceMapper.findByUserName(mobile);
        if(myUserDetails == null){
            return AjaxResponse.error(
                    new CustomException(CustomExceptionType.USER_INPUT_ERROR
                    ,"您输入的手机号不是系统注册用户")
            );
        }

        SmsCode smsCode = new SmsCode(
                RandomStringUtils.randomNumeric(4),60,mobile);
        //TODO 此处调用验证码发送服务接口
        log.info(smsCode.getCode() + "=》" + mobile);

        session.setAttribute("sms_key",smsCode);

        return AjaxResponse.success("短信息已经发送到您的手机");
    }
}